package com.ysucode.service.user.impl;

import com.ysucode.dao.battle.PkUserMapper;
import com.ysucode.dao.user.RoleMapper;
import com.ysucode.dao.user.UserMapper;
import com.ysucode.domain.PkUser;
import com.ysucode.domain.Role;
import com.ysucode.domain.User;
import com.ysucode.service.user.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Transactional //开启事务
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private PkUserMapper pkUserMapper;

    @Override
    public User getByUsernamePassword(String username, String password) {
        return userMapper.getByUsernamePassword(username, password);
    }

    @Override
    public User getByUsername(String username) {
        return userMapper.getByUsername(username);
    }

    @Override
    public Integer addUser(User user) {
        int flag1 = userMapper.addUser(user);
        Integer id = userMapper.getByLastOfId();
        PkUser pkUser = new PkUser(id, 1200, 0, 0);
        int flag2 = pkUserMapper.addUserPk(pkUser);
        return flag1 == 1 && flag1 == flag2 ? 1 : 0;
    }

    @Override
    public User getById(int id) {
        return null;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //security会自己判断密码是否正确，这里根据用户名查询用户
        User user = userMapper.getByUsername(username);
        if (user == null) {
            return null;
        }
        List<GrantedAuthority> authorities = new ArrayList<>();
        //查询角色
        Role role = roleMapper.getById(user.getRole_id());
        //添加角色
        authorities.add(new SimpleGrantedAuthority(role.getName()));
        //创建security中的userDetails对象
        UserDetails userDetails = new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), authorities);
        return userDetails;
    }
}
